Context Managers and with Blocks


In [1]:
with open('clockdeco.py') as fp:
    src = fp.read(60)

In [2]:
len(src)


Out[2]:
60

In [3]:
fp


Out[3]:
<_io.TextIOWrapper name='clockdeco.py' mode='r' encoding='cp1252'>

In [4]:
fp.closed, fp.encoding


Out[4]:
(True, 'cp1252')

In [5]:
fp.read(60)


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-5fbd86132515> in <module>()
----> 1 fp.read(60)

ValueError: I/O operation on closed file.

In [33]:
from mirror import LookingGlass

In [2]:
with LookingGlass() as what:
    print('Alice, Kitty and Snowdrop')
    print(what)


pordwonS dna yttiK ,ecilA
YKCOWREBBAJ

In [8]:
from mirror import LookingGlass
manager = LookingGlass()
manager


Out[8]:
<mirror.LookingGlass at 0x86cd35afd0>

In [13]:
monster = manager.__enter__()

In [14]:
monster == 'JABBERWOCKY'


Out[14]:
True

In [15]:
monster


Out[15]:
'JABBERWOCKY'

In [16]:
manager


Out[16]:
<mirror.LookingGlass at 0x86cd35afd0>

In [17]:
manager.__exit__(None, None, None)

In [18]:
monster


Out[18]:
'JABBERWOCKY'

Using @contextmanager


In [21]:
# from mirror_gen import looking_glass
# with looking_glass() as what:
#     print('Alice, Kitty and Snowdrop')
#     print(what)

In [24]:
import contextlib

@contextlib.contextmanager
def looking_glass():
    import sys
    original_write = sys.stdout.write
    
    def reverse_write(text):
        original_write(text[::-1])
        
    sys.stdout.write = reverse_write
    msg = ''
    try:
        yield 'JABBERWOCKY'
    except ZeroDivisionError:
        msg = 'Please DO NOT divice by zero!'
    finally:
        sys.stdout.write = original_write
        if msg:
            print(msg)

In [ ]: